package com.xxxx.system.controller;

import com.xxxx.server.dto.ChapterDto;
import com.xxxx.server.dto.ResponseDto;
import com.xxxx.server.exception.BusinessException;
import com.xxxx.server.exception.ValidatorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 统一异常处理、数据预处理等
 */
@ControllerAdvice // 控制器增强注解
public class ControllerExceptionHandler {
    private static final Logger LOG = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    // 所有抛此异常的controller都会被这个拦截
    @ExceptionHandler(value = ValidatorException.class)
    @ResponseBody
    public ResponseDto validatorExceptionHandler(ValidatorException e) {
        ResponseDto<ChapterDto> responseDto = new ResponseDto<>();
        responseDto.setSuccess(false);
        // 不能直接把详细的异常信息抛给前端,以免被人利用
        // responseDto.setMessage(e.getMessage());
        LOG.warn(e.getMessage());
        responseDto.setMessage("请求参数异常");
        return responseDto;
    }

    // 所有抛此异常的controller都会被这个拦截
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public ResponseDto businessExceptionHandler(BusinessException e) {
        ResponseDto<ChapterDto> responseDto = new ResponseDto<>();
        responseDto.setSuccess(false);
        LOG.error("业务异常: {}", e.getCode().getDesc());
        responseDto.setMessage(e.getCode().getDesc());
        return responseDto;
    }
}
